﻿
using UnityEngine;
using UnityEditor;
using LitJson;

namespace GameBoxTools
{
    /// <summary>
    /// 检测UI prefab中的指定组件
    /// </summary>
    public class PrefabCheckTool : EditorWindow
    {
        //获取粒子系统
        public static JsonData GetParticleSystem()
        {
            //获取文件夹底下所有prefab文件路径
            string projectDataPath = Application.dataPath.Substring(0, Application.dataPath.Length - 6);
            var allPrePath = Common.GetItemsPathFromDir(".prefab");
            if (allPrePath == null) return null;

            Common.ShowProgress(allPrePath.Length, 0);
            int i = 0;
            bool isAdd = false;
            JsonData info = new JsonData();
            info["prefabs"] = new JsonData();
            foreach (var item in allPrePath)
            {
                string newPath = item.Remove(0, projectDataPath.Length);
                GameObject prefab = AssetDatabase.LoadAssetAtPath<GameObject>(newPath);

                var allParticleSystem = GetPrefabPath(prefab);
                if (null != allParticleSystem)
                {
                    info["prefabs"].Add(allParticleSystem);
                    isAdd = true;
                }

                Common.ShowProgress(allPrePath.Length, ++i);
            }

            Common.CloseProgress();
            AssetDatabase.Refresh();

            return isAdd ? info : null;
        }

        static JsonData GetPrefabPath(GameObject prefab)
        {
            if (null == prefab) return null;
            GameObject newGo = PrefabUtility.InstantiatePrefab(prefab) as GameObject;

            JsonData info = new JsonData();
            bool isHaveComponent = false;
            ParticleSystem[] ts = newGo.GetComponentsInChildren<ParticleSystem>(true);

            if (null != ts && ts.Length > 0)
            {
                for (int i = 0; i < ts.Length; i++)
                {
                    if (null != ts[i])
                    {
                        if (!isHaveComponent)
                        {
                            info["prefab"] = AssetDatabase.GetAssetPath(prefab);
                            isHaveComponent = true;
                        }

                        JsonData prefab_info = new JsonData();
                        prefab_info["name"] = HierarchyHelper.GetHierarchyPath(ts[i].transform);

                        info["Ignore"] = 0;

                        if (!info.Keys.Contains("coms")) info["coms"] = new JsonData();

                        info["coms"].Add(prefab_info);
                    }
                }
            }

            if (null != newGo)
                DestroyImmediate(newGo);

            return isHaveComponent ? info : null;
        }
    }
}